package mapper_core

import (
	"reflect"
)

// 表信息结构体
type TableColumnInfo struct {
	ColumnName      string
	FieldName       string
	StructFieldType reflect.StructField
}

var tableInfoMap = map[string][]TableColumnInfo{}

// 获取表结构信息
func GetTabelInfo(reflectType reflect.Type) []TableColumnInfo {

	typeName := reflectType.Name()

	if tableInfoMap[typeName] != nil {

		return tableInfoMap[typeName]
	}

	var fieldValueMap []TableColumnInfo = []TableColumnInfo{}

	for i := 0; i < reflectType.NumField(); i++ {

		field := reflectType.Field(i)

		if field.Type.Kind() == reflect.Struct { //一层结构体

			for i := 0; i < field.Type.NumField(); i++ {

				f := field.Type.Field(i)

				columnName := f.Tag.Get("db")

				if columnName == "" {

					continue
				}

				fieldValueMap = append(fieldValueMap, TableColumnInfo{ColumnName: columnName, FieldName: f.Name, StructFieldType: f})

			}
		} else { //非结构体 正常字段
			columnName := field.Tag.Get("db")

			if columnName == "" {

				continue
			}

			fieldValueMap = append(fieldValueMap, TableColumnInfo{ColumnName: columnName, FieldName: field.Name, StructFieldType: field})

		}

	}

	tableInfoMap[typeName] = fieldValueMap //缓存表名，避免重复反射获取表名

	return tableInfoMap[typeName]

}
